package com.pan.crawler.impl9;

import com.pan.crawler.Directory;
import com.pan.entity.BookDirectory;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class DirectoryImpl9 implements Directory {

    private String webUrl = "www.22biqu.com";


    @Override
    public BookDirectory get(String url) {
        if (url.indexOf(webUrl) == -1){
            throw new RuntimeException("网址错误："+url+"该网址不是"+webUrl+"网址");
        }
        EdgeDriver edgeDriver = new EdgeDriver();
        edgeDriver.navigate().to(url);
        String bookName = edgeDriver.findElement(By.className("top")).findElement(By.tagName("h1")).getText().trim();
        BookDirectory bookDirectory = new BookDirectory();
        bookDirectory.setBookName(bookName);
        List<Chapter> chapters = new LinkedList<>();
        bookDirectory.setChapterList(chapters);
        String[] directoryPageUrl = edgeDriver.findElement(By.tagName("select")).findElements(By.tagName("option")).stream()
                .map(option->
                option.getAttribute("value")
        ).map(s->webUrl +s).toArray(String[]::new);
        int id = 0;
        for (int i = 0; i < directoryPageUrl.length; i++) {
            String dpUrl = directoryPageUrl[i];
//            System.out.println(dpUrl);//debug
            edgeDriver.navigate().to("https://"+dpUrl);
            WebElement[] aElement = edgeDriver.findElements(By.className("section-box")).get(1)
                    .findElements(By.tagName("a")).stream().toArray(WebElement[]::new);
            for (WebElement a : aElement) {
                String title = a.getText();
                String href = a.getAttribute("href");
                Chapter chapter = new Chapter(id++,title,href);
                chapters.add(chapter);
            }
        }
        edgeDriver.quit();
        return bookDirectory;
    }

    public static void main(String[] args) {
        DirectoryImpl9 directoryImpl9 = new DirectoryImpl9();
        directoryImpl9.get("https://www.22biqu.com/biqu80882/");
    }
}
